package com.thoughtworks.util.http;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class PostRequestExecutor implements RequestExecutor {
    private static final Logger logger = Logger.getLogger(PostRequestExecutor.class);

    private HttpClient httpClient;
    private PostMethod postMethod;

    public PostRequestExecutor(HttpClient httpClient, PostMethod postMethod) {
        this.httpClient = httpClient;
        this.postMethod = postMethod;
    }

    public void execute(Object requestData, HttpResponseHandler handler) {
        Map<String, String> postdata = (Map<String, String>) requestData;
        postMethod.setRequestBody(AndrosphereUtils.convertToNameValuePair(postdata));
        try {
            int responseCode = httpClient.executeMethod(postMethod);
            Header[] headers = postMethod.getRequestHeaders();

            handler.handle(responseCode, AndrosphereUtils.convertToMap(headers), postMethod.getResponseBodyAsStream());
        } catch (IOException e) {
            String message = "Error executing POST request to URL: " + getUrl();
            logger.error(message, e);
            throw new HttpTemplateException(message, e);
        } finally {
            postMethod.releaseConnection();
        }
    }

    public void setRequestHeader(String headerName, String headerValue) {
        postMethod.setRequestHeader(headerName, headerValue);
    }

    public String getUrl() {
        try {
            return postMethod.getURI().toString();
        } catch (URIException e) {
            e.printStackTrace();
        }
        return null;
    }
}
